package com.mzba.place.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.SimpleAdapter;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.google.gson.Gson;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.adapter.ReportListAdapter;
import com.mzba.place.entity.ReportEntity;
import com.mzba.place.entity.ReportInfoGson;
import com.mzba.place.ui.MainActivity;
import com.mzba.place.ui.ReportDetailActivity;
import com.mzba.place.ui.widget.CustomListView;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.BasicUIEvent;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.ImageLoader;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
/**
 * 
 * @author 06peng
 *
 */
public class MyStarFragment extends SherlockFragment implements Callback, BasicUIEvent  {
	
	private MainActivity mainActivity;
	private CustomListView listView;
	private List<ReportEntity> reports;
	private ReportEntity entry;
	private ReportListAdapter reportListAdapter;
	private ImageLoader mImageLoader;
	private double localLat;
	private double localLon;
	public PlaceApplication app;
	public LocationClient mLocClient;
	private Handler handler;
	
	private final int init_reports = 1;
	private final int delete_report = 2;
	
	private final int menu_delete = 3;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity = (MainActivity) getSherlockActivity();
		handler = new Handler(this);
		app = (PlaceApplication) mainActivity.getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(mainActivity);
            app.mBMapManager.init(PlaceApplication.strKey, new PlaceApplication.MyGeneralListener());
        }
        app.getMyListener().setHander(handler);
        mLocClient = app.mLocationClient;
		mImageLoader = ImageLoader.getInstance(mainActivity);
		menuMyPosition();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_report_list, null);
		listView = (CustomListView) view.findViewById(R.id.list_report);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Intent intent = new Intent();
				intent.setClass(mainActivity, ReportDetailActivity.class);
				if (reportListAdapter!=null) {
					intent.putExtra("report_detail", reportListAdapter.getReportList().get(arg2-1));
					startActivity(intent);
				}
				
			}
		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (reports != null && !reports.isEmpty()) {
					entry = reports.get(arg2 - 1);
					mainActivity.startActionMode(new AnActionModeOfNewsProportions());
				}
				return true;
			}
		});
		
		return view;
	}
	
	/* (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		super.onResume();
		UICore.eventTask(this, mainActivity, init_reports, null, true);
	}

	OnScrollListener onScrollListener = new OnScrollListener() {
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_FLING:
				mImageLoader.lock();
				break;
			case OnScrollListener.SCROLL_STATE_IDLE:
				mImageLoader.unlock();
				break;
			case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				mImageLoader.lock();
				break;
			default:
				break;
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			
		}
	};
	
	/**
	 * locate to my position
	 */
	public void menuMyPosition() {
		new Thread() {
			public void run() {
				setLocationOption();
				if (mLocClient != null && mLocClient.isStarted()) {
					mLocClient.requestLocation();
				} else {
					mLocClient.start();
					mLocClient.requestLocation();
				}
			};
		}.start();
	}
	
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);			
		option.setCoorType("bd09ll");			
		option.setAddrType("all");	
		option.setScanSpan(0);
		option.setPriority(LocationClientOption.GpsFirst);      
		option.setPoiNumber(10);
		option.disableCache(true);		
		mLocClient.setLocOption(option);
	}

	@Override
	public void execute(int mes, Object obj) {
		try {
			String response = null;
			switch (mes) {
			case init_reports:
				String url = UrlConfig.star_reports;
				url += "?auth_token=" + AppContext.getInstance().getAuthToken();
				response = HttpUtils.doGet(url);
				if (StringUtil.isNotBlank(response)) {
					Gson gson = new Gson();
					ReportInfoGson reportGson = gson.fromJson(response, ReportInfoGson.class);
					if (reportGson != null) {
						reports = reportGson.getReports();
					}
				}
				handler.sendEmptyMessage(init_reports);
				break;
			case delete_report:
				String deleteUrl = UrlConfig.un_star(entry.getId() + "");
				HashMap<String, String> paramsMap = new HashMap<String, String>();
				paramsMap.put("auth_token", AppContext.getInstance().getAuthToken());
				response = HttpUtils.doPost(mainActivity, deleteUrl, paramsMap);
				if (getRc(response) == 0) {
					handler.sendEmptyMessage(delete_report);
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_reports:
			if (reports != null && !reports.isEmpty()) {
				reportListAdapter = new ReportListAdapter(mainActivity, reports, localLat, localLon, mImageLoader);
				listView.setAdapter(reportListAdapter);
			} else {
				List<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("value", "暂无数据");
				data.add(map);
				SimpleAdapter adapter = new SimpleAdapter(mainActivity, data, R.layout.empty_listitem, 
						new String[] {"value"}, new int[] {R.id.value});
				listView.setAdapter(adapter);
			}
			break;
		case AppContext.LOCATE:
			localLat = app.latitude;
			localLon = app.longitude;
			break;
		case delete_report:
			try {
				reports.remove(entry);
				if (reports != null && !reports.isEmpty()) {
					reportListAdapter.notifyDataSetChanged();
				} else {
					List<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("value", "暂无数据");
					SimpleAdapter adapter = new SimpleAdapter(mainActivity, data, R.layout.empty_listitem, 
							new String[] {"value"}, new int[] {R.id.value});
					listView.setAdapter(adapter);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		default:
			break;
		}
		return false;
	}

	private int getRc(String json) {
		JSONObject jsonObject;
		int rc = 1;
		try {
			jsonObject = new JSONObject(json);
			rc = jsonObject.getInt("rc");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return rc;
	}
	
	private final class AnActionModeOfNewsProportions implements ActionMode.Callback {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        	menu.add(0, menu_delete, 0, "删除").setIcon(R.drawable.icon_delete).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
			case menu_delete:
				mode.finish();
				UICore.eventTask(MyStarFragment.this, mainActivity, delete_report, null, true);
				break;

			default:
				break;
			}
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
        	
        }
    }
}
